﻿using SharpConfig;
using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;

namespace LL2025.Ini.Lib
{
    public static class Config
    {
        public static bool StringToBool(this string c) => c == "是";
        public static string BoolToString(this bool c) => c ? "是" : "否";
        private static readonly string configpath = AppDomain.CurrentDomain.BaseDirectory + "配置文件.ini";


        public static async Task<bool> CreateUpdateConfigAsync(object o)
        {
            return await IniConfig.Path(configpath, IniConfig.IniType.Write)
                                   .CreateSectionsFromOneObject(o)
                                   .SaveCacheToFileAsync();
        }

        public static bool CreateUpdateConfigConfig(object o)
        {
            return IniConfig.Path(configpath, IniConfig.IniType.Write)
                                   .CreateSectionsFromOneObject(o)
                                   .SaveCacheToFile();
        }
        public static bool CreateOrUpdateConfig(object o)
        {
            Configuration cfg = IniConfig.Path(configpath, IniConfig.IniType.Write)
                                .CreateSectionsFromOneObject(o);
            cfg.SaveToFile(configpath);
            return true;
        }

        public static T ReaderConfig<T>(this object o) where T : new()
        {
            if (!File.Exists(configpath)) CreateOrUpdateConfig(o);
            var cfg = IniConfig.Path(configpath);
            return cfg.LoadFromIFile<T>();
        }
        public static bool AreEqual(object obj1, object obj2)
        {
            if (obj1 == null || obj2 == null)
                return obj1 == obj2;

            if (obj1.GetType() != obj2.GetType())
                return false;

            Type type = obj1.GetType();
            foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (!property.CanRead) continue;

                object value1 = property.GetValue(obj1);
                object value2 = property.GetValue(obj2);

                // 比较基本类型和字符串
                if (value1 is ValueType || value1 is string)
                {
                    if (!object.Equals(value1, value2))
                        return false;
                }
                else if (value1 != null && value2 != null)
                {
                    // 对于引用类型，递归比较
                    if (!AreEqual(value1, value2))
                        return false;
                }
                else if (value1 != value2)
                {
                    // 如果其中一个为null而另一个不是，则不相等
                    return false;
                }
            }

            return true;
        }

    }

}
